import { Tag } from '@/components';
import { useGlobalVar } from '@/hooks';
import React, { useState, useMemo } from 'react';
import { TUser } from '@/types';

type Member = {
   userId: string;
   username: string;
};
type Props<T> = {
   initValue?: T[];
   onChange?: (value: T[]) => void;
};

const MembersSelector: React.FC<Props<Member>> = ({ initValue, onChange }) => {
   const [value, setValue] = useState(initValue);
   const { group, user } = useGlobalVar();

   const handleChange = (user) => {
      const isExist = value.find((item) => item.userId === user._id);
      if (isExist) {
         const data = value.filter((item) => item.userId !== user._id);
         setValue(data);
         onChange && onChange(data);
      } else {
         const data = [...value, { userId: user._id, username: user.username }];
         setValue(data);
         onChange && onChange(data);
      }
   };

   const getBg = useMemo(
      () => (id: string) => {
         const isExist = value.some((item) => item.userId === id);
         return isExist ? 'primary' : 'default';
      },
      [value]
   );

   if (!group) return <div>Loading...</div>;
   const members = group.members as Array<TUser>;

   return (
      <div className="w-full flex-base items-start">
         <span className="text-sm">成员</span>
         <div className="flex space-x-2">
            {members.map((item) => (
               <Tag
                  key={item._id}
                  onClick={handleChange.bind(null, item)}
                  type={getBg(item._id)}
               >
                  {item._id === user._id ? '我' : item.username}
               </Tag>
            ))}
         </div>
      </div>
   );
};
export default MembersSelector;
